package cn.edu.njust.bio;

import cn.edu.njust.EchoServer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;

@Slf4j
public class BioEchoServer implements EchoServer {

    private ServerSocket serverSocket;

    private static String recv(Socket socket) {

        try {
            InputStream in = socket.getInputStream();
            // 用readAllBytes比较方便
            return new String(in.readAllBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static void send(Socket socket, String message) {
        try {
            OutputStream out = socket.getOutputStream();
            out.write(message.getBytes());
            // 发完消息记得关闭输出，否则会导致客户端read一直阻塞！(这里不采用拆包机制)
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen(int port) {
        try {
            this.serverSocket = new ServerSocket();
            this.serverSocket.bind(new InetSocketAddress(port));
        } catch (IOException e) {
            log.error("初始化ServerSocket失败");
            e.printStackTrace();
        }
    }

    public void serve() {
        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                log.info("接收客户端{}的连接请求", clientSocket.getRemoteSocketAddress());
                // Read message
                String messae = recv(clientSocket);
                log.info("从客户端{}收到{}", clientSocket.getRemoteSocketAddress(), messae);
                // Send message
                send(clientSocket, messae);
                log.info("发送Echo消息{}给客户端{}", messae, clientSocket.getRemoteSocketAddress());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
